<?php

namespace app\base\model;

use app\common\model\Base;
use think\Cache;

class Department extends Base {
  protected $name = 'base_department';
  protected static $cacheName = 'cacheDept';
  protected static $cacheTag = 'dept';

  protected $auto = ['is_hide',
                     'is_branch'];

  public function initialize() {
    parent::initialize();
  }

  protected static function init() {
    $cacheTag = self::$cacheTag;
    Self::afterDelete(function ($data) use ($cacheTag) {
      Cache::clear($cacheTag);
    });
    Self::afterWrite(function ($data) use ($cacheTag) {
      Cache::clear($cacheTag);
    });
  }

  public function setIsHideAttr($value, $data) {
    return (!$value) ? 0 : $value;
  }

  public function setIsBranchAttr($value, $data) {
    return (!$value) ? 0 : $value;
  }

  public function getShortAttr($value, $data) {
    return (!($value)) ? $data['title'] : $value;
  }

  public function getShortFullAttr($value, $data) {
    //$dept= $this->cache_by_id($data['parent_id']);
    return $value;
  }

  public function edit($form, $id = 0) {
    return parent::edit($form, $id);
  }

  /**
   * 获取当前所有的子部门的ID
   * @param $department_id
   * @param null $departments
   * @return array
   */

  public function children_all($department_id, $departments = NULL) {
    $departments == NULL && $departments = $this->cache_departments();
    $arr = $arr2 = [$department_id];
    foreach ($departments as $id => $v) {
      if ($v['parent_id'] == $department_id) {
        $arr[] = $id;
        $arr2 = array_merge($arr, $this->children($id, $departments));
      }
    }

    return $arr2;
  }

  /**仅仅当前下面一级的子部门的ID
   * @param $department_id
   * @param null $departments
   * @return array
   */
  public function children($department_id, $departments = NULL) {
    $departments == NULL && $departments = $this->cache_departments();
    $arr = [];
    foreach ($departments as $id => $v) {
      if ($v['parent_id'] == $department_id) {
        //$arr[$id] = $v['title'];
        $arr[] = $id;
      }
    }

    return $arr;
  }

  /**
   * 返回树形部门菜单
   * @return array
   */

  public function select() {
    return parent::data2select($this->cacheDepartments(), 0);
  }

  /**
   * 缓存部门资料
   * @return array|mixed
   */

  public function cacheDepartments() {
    $depts = Cache::get(self::$cacheName, NULL);
    if (!$depts) {
      $depts = $this->order('sort DESC,id ASC')->column('id,title,parent_id', 'id');
      Cache::tag(self::$cacheTag)->set(self::$cacheName, $depts);
    }

    return $depts;
  }

  function cacheName($id, $short = FALSE) {
    $row = parent::cacheRow($id);
    if (!$row) return '未分配部门';

    return $short ? $row['short'] : $row['title'];
  }

  /**
   * 查找部门负责人，自动向上追溯
   * @param int $department_id
   * @return bool
   */

  function getManagerUid($department_id = 0) {
    if ($department_id === NULL) $department_id = xs_department_id_by_uid(session('userid'));
    if ($department_id == 0) return FALSE;

    $department = self::cacheRow($department_id);
    if ($department['manager_uid'] > 0) {
      return $department['manager_uid'];
    }

    return self::getManagerUid($department['parent_id']);
  }

  /**
   * 获取顶部一级部门
   * @param int $department_id
   * @return mixed
   */
  public function getTopDepartment($department_id = 0) {
    $department = self::cacheRow($department_id);
    if ($department['parent_id'] > 1) {
      return $this->getTopDepartment($department['parent_id']);
    }

    return $department;
  }

  /**
   * 获取顶部一级部门ID
   * @param int $department_id
   * @return mixed
   */
  public function getTopDepartmentID($department_id = 0) {
    return $this->getTopDepartment($department_id)['id'];
  }

  public function getTopManagerUid($department_id = 0) {
    $dept_id = $this->getTopDepartmentID($department_id);

    $department = self::cacheRow($dept_id);

    return $department['manager_uid'];
  }

  public function getFullName($department_id) {
    $parent_id = $this->getTopDepartmentID($department_id);
    if ($parent_id == $department_id) {
      return self::cacheName($department_id);
    } else {
      return self::cacheName($parent_id) . '-' . self::cacheName($department_id);
    }
  }

  public function getShortName($parent_id = 1, $is_branch = FALSE) {
    $map = ['parent_id' => $parent_id,
            'is_hide'   => 0];
    if ($is_branch === 1) {
      $map['is_branch'] = 1;
    } elseif ($is_branch === 0) {
      $map['is_branch'] = 0;
    }
    $rows = $this->where($map)->column('short,title', 'id');
    $data = [];
    foreach ($rows as $id => $row) {
      $data[ $id ] = ['id'    => $id,
                      'short' => (empty($row['short'])) ? $row['title'] : $row['short'],
      ];
    }

    return $data;
  }

  public function getBranch($sub = TRUE) {
    $map = ['is_branch' => 1,
            'is_hide'   => 0];
    $rows = $this->where($map)->column('id');
    $data = $rows;
    foreach ($rows as $dept_id) {
      $data = array_merge($data, $this->children_all($dept_id));
    }

    return $data;
  }

  /**
   * 获取一级部门以及当前部门的联合名称
   * @param $dept_id
   * @param bool $short
   * @return mixed|string
   */

  public function dept_fullname($dept_id, $short = TRUE) {
    $lv1 = $this->get_lv1_department_id($dept_id);
    if ($lv1 == $dept_id)
      return $this->cache_name($dept_id);
    $name = $this->cache_name($this->get_lv1_department_id($dept_id), $short);
    $name .= '-';
    $name .= $this->cache_name($dept_id, $short);

    return $name;
  }

}